package com.ruoyi.web.controller.wechat;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.wechat.domain.WxQrCode;
import com.ruoyi.wechat.domain.WxQrCodeForm;
import com.ruoyi.wechat.service.WxQrCodeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpQrCodeTicket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;

/**
 * 公众号带参二维码管理
 * https://github.com/Wechat-Group/WxJava/wiki/MP_二维码管理
 *
 * @author 26233
 */
@RestController
@RequestMapping("/manage/wxQrCode")
@Api(tags = {"公众号带参二维码-管理后台"})
public class WxQrCodeManageController {
    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private WxQrCodeService wxQrCodeService;
    @Autowired
    private WxMpService wxMpService;

    /**
     * 创建带参二维码ticket
     */
    @PostMapping("/createTicket")
    @ApiOperation(value = "创建带参二维码ticket", notes = "ticket可以换取二维码图片")
    public AjaxResult createTicket(@RequestBody WxQrCodeForm form) throws WxErrorException {
        wxMpService.switchoverTo(form.getAppid());
        WxMpQrCodeTicket ticket = wxQrCodeService.createQrCode(form.getAppid(), form);
        return AjaxResult.success(ticket);
    }

    /**
     * 列表
     */
    @GetMapping("/list")
    @ApiOperation(value = "列表")
    public AjaxResult list(Page page, WxQrCode wxQrCode) {
        QueryWrapper<WxQrCode> queryWrapper = new QueryWrapper<WxQrCode>()
                .like(StringUtils.isNotBlank(wxQrCode.getSceneStr()), "scene_str", wxQrCode.getSceneStr());

        return AjaxResult.success("列表", wxQrCodeService.page(page, queryWrapper));
    }


    /**
     * 信息
     */
    @GetMapping("/info/{id}")
    @ApiOperation(value = "详情")
    public AjaxResult info(String appid, @PathVariable("id") Long id) {
        WxQrCode wxQrCode = wxQrCodeService.getById(id);

        return AjaxResult.success("wxQrCode", wxQrCode);
    }

    /**
     * 删除
     */
    @PostMapping("/delete")
    @ApiOperation(value = "删除")
    public AjaxResult delete(String appid, @RequestBody Long[] ids) {
        wxQrCodeService.removeByIds(Arrays.asList(ids));
        return AjaxResult.success();
    }
}
